<?php
namespace app\data_magic\controller;

use think\Controller;


class WidgetController extends Controller
{
    /**
     * 获取tab控件
     */
    public function fetchTab()
    {

    }
    /**
     * 获取filter控件
     */
    public function fetchFilter()
    {

    }
    /**
     * 获取form控件
     */
    public function fetchForm()
    {

    }
    /**
     * 获取table控件
     */
    public function fetchTable()
    {

    }
    /**
     * 获取tree-table控件
     */
    public function fetchTreeTable()
    {

    }
    
    /**
     * 解析字段参数设置
     * 返回字段列表
     * @param FieldData[] $fields 字段设置
     * @param array $list 数据列表
     * @return array
     */
    protected function parseEditorParams($fields,$item=[])
    {
        $result=[];
        foreach($fields as $field){
            $struct=new FormField($field);
            $field_name=$field->name;
            if(in_array($field->type,["select","radio","checkbox"])){
                $options=StringParams::option($field->type_params);
                $option_list=[];
                foreach($options as $name => $title){
                    $option_list[]=["name"=>$name,"title"=>$title,"selected"=>false];
                }
                if(isset($item[$field_name])){
                    $value = explode(",",$item[$field_name]);
                    foreach($option_list as &$option_item){
                        if(in_array($option_item["name"],$value)){
                            $option_item["selected"]=true;
                        }
                    }
                    $struct->selected=$value;
                }
                $struct->options=$option_list;
            }
            elseif(in_array($field->type,["datetime","date"])){
                $struct->time = isset($item[$field_name]) ? $item[$field_name] : time();
            }
            elseif($field->type==="time"){
                if(isset($item[$field_name])){
                    $struct->time = $item[$field_name] ;
                }
                else{
                    //获取今天零时到现在的秒数
                    $format_time=date("Y-m-d",0) .' '. date("H:i:s",time());
                    $struct->time=date_create_from_format("Y-m-d H:i:s",$format_time)->getTimestamp();
                }
            }
            elseif(in_array($field->type,["images","files"])){
                $items = [];
                if(isset($item[$field_name]) && $item[$field_name]){
                    $items = json_decode($item[$field_name],true);
                }
                $struct->uploaded=$items;
            }
            elseif($field->type==="location"){
                if(isset($item[$field_name]) && $item[$field_name]){
                    $struct->location=json_decode($item[$field_name],true);
                }
            }
            elseif(in_array($field->type,["refer"])){
                if(isset($item[$field_name]) && $item[$field_name]){
                    $params=StringParams::assoc(["table_name","action_id","id_field","name_field"],$field->type_params);
                    $refer=Db::table($params["table_name"])
                        ->field($params["id_field"].",".$params["name_field"])
                        ->where($params["id_field"]." in ({$item[$field_name]})")->select();
                    $id_list=[];
                    $name_list=[];
                    foreach($refer as $refer_item){
                        $id_list[]=$refer_item[$params["id_field"]];
                        $name_list[]=$refer_item[$params["name_field"]];
                    }
                    $struct->referred=[
                        "ids"=>$id_list,
                        "names"=>$name_list
                    ];
                }
            }
            elseif($field->type==="color"){
                $struct->value = isset($item[$field_name]) ? $item[$field_name] : "#000000";
            }
            else{
                if(isset($item[$field_name])){
                    $struct->value = $item[$field_name] ;
                }
            }

            $result[$field_name]=$struct;
        }
        return $result;
    }
    
    /**
     * 将字段编辑Widget输入的数据转换成内部数据
     * @param Result $result 结果对象
     */
    public function convertInputData($result,$item)
    {
        foreach($result->fields as $field){
            $field_name=$field->name;
            if(!$field->writable){
                continue;
            }
            elseif(in_array($field->type,["select","radio","checkbox","refer"])){
                if(isset($item[$field_name]) && is_string($item[$field_name])){
                    $item[$field_name]=explode(",",$item[$field_name]);
                }
            }
            elseif(in_array($field->type,["datetime","date","time"])){
                if(isset($item[$field_name])){
                    $format_map=["datetime"=>"Y-m-d H:i","date"=>"Y-m-d","time"=>"H:i:s"];
                    $item[$field_name]=date_create_from_format($format_map[$field->type],$item[$field_name])->getTimestamp();
                }
            }
            elseif(in_array($field->type,["images","files"])){
                if(isset($item[$field_name."_urls"]) && isset($item[$field_name."_names"])){
                    $urls = $item[$field_name."_urls"];
                    $names = $item[$field_name."_names"];
                    $file_list=[];
                    foreach($urls as $index=>$url){
                        $file_list[] = [
                            "url"=>$url,
                            "name"=>isset($names[$index]) ? $names[$index] : ""
                        ];
                    }
                    $item[$field_name]=$file_list;
                }
            }
            elseif($field->type==="location"){
                if(isset($item[$field_name])){
                    $location = ["text"=>"","longitude"=>0,"latitude"=>0];
                    $location_params=explode(",",$item[$field_name]);
                    if(count($location_params)===2){
                        $location["longitude"]=$location_params[0];//经度
                        $location["latitude"]=$location_params[1];//纬度
                    }
                    if(isset($item[$field_name."_text"])){
                        $location["text"]=$item[$field_name."_text"];
                    }
                    $item[$field_name]=$location;
                }
            }
            elseif($field->type==="html"){
                if(isset($item[$field_name])){
                    $html=htmlspecialchars_decode($item[$field_name]);//将转码过的HTML代码恢复
                    $html=cmf_replace_content_file_url($html, true);//替换内容中的文件链接
                    $item[$field_name]=htmlspecialchars($html);//将HTML代码重新转码
                }
            }
        }
        return $item;
    }
    
    /**
     * 将列表中所有的值转换成相应的字符串
     * 返回$data_list
     * @param FieldData[] $fields 字段设置
     * @param array $list 数据列表
     * @return array
     */
    protected function convertToString($fields,$list)
    {
        $result=[];
        foreach($list as $index => $item){
            foreach($fields as $field){
                $field_name=$field->name;
                $value="";
                if(in_array($field->type,["select","radio","checkbox"])){
                    $options=StringParams::option($field->type_params);
                    $value = $item[$field_name];
                    $value = isset($options[$value]) ? $options[$value] : $value ;
                }
                elseif($field->type==="refer"){
                    $params=StringParams::assoc(["table_name","action_id","id_field","name_field"],$field->type_params);
                    $refer=Db::table($params["table_name"])
                        ->field($params["id_field"].",".$params["name_field"])
                        ->where($params["id_field"]." in ({$item[$field_name]})")->select();
                    $name_list=[];
                    foreach($refer as $refer_item){
                        $name_list[]=$refer_item[$params["name_field"]];
                    }
                    $value=implode(" ",$name_list);
                }
                elseif(in_array($field->type,["datetime"])){
                    $value=date("Y-m-d H:i:s",$item[$field_name]);
                }
                elseif(in_array($field->type,["date"])){
                    $value=date("Y年m月d日",$item[$field_name]);
                }
                elseif(in_array($field->type,["images","files"])){
                    if($item[$field_name]){
                        $uploaded=json_decode($item[$field_name],true);
                        $upload_names=[];
                        foreach($uploaded as $upload_item){
                            $upload_names[]=$upload_item["name"];
                        }
                        $value=implode(" ",$upload_names);
                    }
                }
                elseif($field->type==="location"){
                    if($item[$field_name]){
                        $location=json_decode($item[$field_name],true);
                        $value=$location["text"];
                    }
                }
                else{
                    $value=$item[$field_name];
                }
                $result[$index][$field_name]=$value;
            }
        }
        return $result;
    }
}
